"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Progress } from "@/components/ui/progress"
import {
  ArrowLeft,
  BookOpen,
  Search,
  Filter,
  Star,
  Clock,
  User,
  Eye,
  Heart,
  MessageSquare,
  Download,
  Share2,
  Bookmark,
  TrendingUp,
  Award,
  Target,
  Lightbulb,
  BarChart3,
  Users,
  Building,
  Globe,
  ChevronRight,
  Tag,
  FileText,
  Video,
  Image,
  ThumbsUp,
  ThumbsDown,
  CheckCircle
} from "lucide-react"

interface KnowledgeArticle {
  id: string
  title: string
  summary: string
  content: string
  category: string
  subcategory: string
  difficulty: "beginner" | "intermediate" | "advanced"
  readTime: number
  author: string
  publishDate: string
  tags: string[]
  likes: number
  views: number
  comments: number
  rating: number
  type: "article" | "video" | "infographic" | "checklist" | "template"
  bookmarked: boolean
  liked: boolean
}

export default function KnowledgeBasePage() {
  const router = useRouter()
  const [searchTerm, setSearchTerm] = useState("")
  const [selectedCategory, setSelectedCategory] = useState("all")
  const [selectedDifficulty, setSelectedDifficulty] = useState("all")
  const [selectedType, setSelectedType] = useState("all")
  const [sortBy, setSortBy] = useState("latest")
  const [selectedArticle, setSelectedArticle] = useState<KnowledgeArticle | null>(null)
  const [articles, setArticles] = useState<KnowledgeArticle[]>([])
  const [loading, setLoading] = useState(true)
  const [currentUser, setCurrentUser] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(true)

  const categories = [
    { id: "all", name: "全部", icon: Globe, color: "bg-blue-500" },
    { id: "strategy", name: "商业策略", icon: Target, color: "bg-green-500" },
    { id: "marketing", name: "市场营销", icon: TrendingUp, color: "bg-purple-500" },
    { id: "finance", name: "财务管理", icon: BarChart3, color: "bg-orange-500" },
    { id: "operations", name: "运营管理", icon: Building, color: "bg-blue-500" },
    { id: "leadership", name: "领导力", icon: Users, color: "bg-red-500" },
    { id: "innovation", name: "技术创新", icon: Lightbulb, color: "bg-yellow-500" },
  ]

  const difficulties = [
    { id: "all", name: "全部难度", color: "bg-gray-500" },
    { id: "beginner", name: "入门", color: "bg-green-500" },
    { id: "intermediate", name: "进阶", color: "bg-yellow-500" },
    { id: "advanced", name: "高级", color: "bg-red-500" },
  ]

  const contentTypes = [
    { id: "all", name: "全部类型", icon: FileText },
    { id: "article", name: "文章", icon: FileText },
    { id: "video", name: "视频", icon: Video },
    { id: "infographic", name: "信息图", icon: Image },
    { id: "checklist", name: "检查清单", icon: CheckCircle },
    { id: "template", name: "模板", icon: FileText },
  ]

  const sortOptions = [
    { id: "latest", name: "最新发布" },
    { id: "popular", name: "最受欢迎" },
    { id: "rating", name: "评分最高" },
    { id: "views", name: "浏览最多" },
  ]

  // Mock knowledge articles data
  const mockArticles: KnowledgeArticle[] = [
    {
      id: "1",
      title: "创业公司如何制定有效的商业策略",
      summary: "深入探讨创业公司在早期阶段如何制定和执行有效的商业策略，包括市场分析、竞争定位和增长规划。",
      content: "详细的商业策略制定指南...",
      category: "strategy",
      subcategory: "business-planning",
      difficulty: "intermediate",
      readTime: 12,
      author: "张伟",
      publishDate: "2024-01-15",
      tags: ["商业策略", "创业", "市场分析", "竞争分析"],
      likes: 145,
      views: 2341,
      comments: 28,
      rating: 4.8,
      type: "article",
      bookmarked: false,
      liked: false
    },
    {
      id: "2",
      title: "数字营销完全指南：从0到1建立品牌影响力",
      summary: "全面介绍数字营销的各个方面，包括社交媒体营销、内容营销、搜索引擎优化和付费广告策略。",
      content: "数字营销完整教程...",
      category: "marketing",
      subcategory: "digital-marketing",
      difficulty: "beginner",
      readTime: 18,
      author: "李明",
      publishDate: "2024-01-10",
      tags: ["数字营销", "品牌建设", "社交媒体", "内容营销"],
      likes: 203,
      views: 3456,
      comments: 45,
      rating: 4.9,
      type: "article",
      bookmarked: true,
      liked: true
    },
    {
      id: "3",
      title: "财务管理基础：现金流管理与预算规划",
      summary: "为创业者和小企业主提供实用的财务管理知识，重点讲解现金流管理和预算规划的方法。",
      content: "财务管理基础知识...",
      category: "finance",
      subcategory: "cash-flow",
      difficulty: "beginner",
      readTime: 15,
      author: "王芳",
      publishDate: "2024-01-08",
      tags: ["财务管理", "现金流", "预算", "会计"],
      likes: 167,
      views: 2890,
      comments: 32,
      rating: 4.7,
      type: "article",
      bookmarked: false,
      liked: false
    },
    {
      id: "4",
      title: "团队管理艺术：如何激发团队潜力",
      summary: "探讨现代团队管理的核心原则，包括团队激励、沟通技巧、冲突解决和绩效管理。",
      content: "团队管理详细指南...",
      category: "leadership",
      subcategory: "team-management",
      difficulty: "advanced",
      readTime: 20,
      author: "陈强",
      publishDate: "2024-01-05",
      tags: ["团队管理", "领导力", "员工激励", "绩效管理"],
      likes: 189,
      views: 2567,
      comments: 38,
      rating: 4.6,
      type: "article",
      bookmarked: true,
      liked: false
    },
    {
      id: "5",
      title: "产品创新流程：从创意到市场",
      summary: "详细介绍产品创新的完整流程，从创意生成、概念验证到产品开发和市场推广。",
      content: "产品创新完整流程...",
      category: "innovation",
      subcategory: "product-development",
      difficulty: "intermediate",
      readTime: 16,
      author: "刘敏",
      publishDate: "2024-01-03",
      tags: ["产品创新", "产品开发", "市场验证", "创意管理"],
      likes: 156,
      views: 2123,
      comments: 29,
      rating: 4.8,
      type: "article",
      bookmarked: false,
      liked: true
    },
    {
      id: "6",
      title: "运营管理优化：提升效率的10个策略",
      summary: "分享企业运营管理的实用策略，帮助企业提升运营效率、降低成本、优化流程。",
      content: "运营管理优化策略...",
      category: "operations",
      subcategory: "efficiency",
      difficulty: "intermediate",
      readTime: 14,
      author: "赵杰",
      publishDate: "2024-01-01",
      tags: ["运营管理", "效率提升", "流程优化", "成本控制"],
      likes: 134,
      views: 1987,
      comments: 22,
      rating: 4.5,
      type: "article",
      bookmarked: false,
      liked: false
    }
  ]

  useEffect(() => {
    // Simulate API call
    setTimeout(() => {
      setArticles(mockArticles)
      setLoading(false)
    }, 1000)
  }, [])

  const filteredArticles = articles.filter(article => {
    const matchesSearch = article.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      article.summary.toLowerCase().includes(searchTerm.toLowerCase()) ||
      article.tags.some(tag => tag.toLowerCase().includes(searchTerm.toLowerCase()))
    const matchesCategory = selectedCategory === "all" || article.category === selectedCategory
    const matchesDifficulty = selectedDifficulty === "all" || article.difficulty === selectedDifficulty
    const matchesType = selectedType === "all" || article.type === selectedType

    return matchesSearch && matchesCategory && matchesDifficulty && matchesType
  })

  const sortedArticles = [...filteredArticles].sort((a, b) => {
    switch (sortBy) {
      case "latest":
        return new Date(b.publishDate).getTime() - new Date(a.publishDate).getTime()
      case "popular":
        return b.likes - a.likes
      case "rating":
        return b.rating - a.rating
      case "views":
        return b.views - a.views
      default:
        return 0
    }
  })

  const handleArticleClick = (article: KnowledgeArticle) => {
    setSelectedArticle(article)
  }

  const handleBookmark = (articleId: string) => {
    setArticles(prev => prev.map(article => 
      article.id === articleId ? { ...article, bookmarked: !article.bookmarked } : article
    ))
  }

  const handleLike = (articleId: string) => {
    setArticles(prev => prev.map(article => 
      article.id === articleId ? { 
        ...article, 
        liked: !article.liked,
        likes: article.liked ? article.likes - 1 : article.likes + 1
      } : article
    ))
  }

  const getDifficultyColor = (difficulty: string) => {
    switch (difficulty) {
      case "beginner": return "bg-green-500"
      case "intermediate": return "bg-yellow-500"
      case "advanced": return "bg-red-500"
      default: return "bg-gray-500"
    }
  }

  const getTypeIcon = (type: string) => {
    switch (type) {
      case "video": return Video
      case "infographic": return Image
      case "checklist": return CheckCircle
      case "template": return FileText
      default: return FileText
    }
  }

  if (selectedArticle) {
    return (
      <div className="min-h-screen bg-gray-50">
        <div className="container mx-auto px-4 py-8">
          <div className="max-w-4xl mx-auto">
            <Button
              variant="ghost"
              className="mb-6"
              onClick={() => setSelectedArticle(null)}
            >
              <ArrowLeft className="h-4 w-4 mr-2" />
              返回知识库
            </Button>

            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle className="text-2xl mb-2">{selectedArticle.title}</CardTitle>
                    <p className="text-gray-600 mb-4">{selectedArticle.summary}</p>
                    <div className="flex items-center gap-4 text-sm text-gray-500">
                      <div className="flex items-center gap-1">
                        <User className="h-4 w-4" />
                        {selectedArticle.author}
                      </div>
                      <div className="flex items-center gap-1">
                        <Clock className="h-4 w-4" />
                        {selectedArticle.readTime} 分钟阅读
                      </div>
                      <div className="flex items-center gap-1">
                        <Eye className="h-4 w-4" />
                        {selectedArticle.views} 次浏览
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleBookmark(selectedArticle.id)}
                    >
                      <Bookmark className={`h-4 w-4 ${selectedArticle.bookmarked ? 'fill-current' : ''}`} />
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleLike(selectedArticle.id)}
                    >
                      <Heart className={`h-4 w-4 ${selectedArticle.liked ? 'fill-current text-red-500' : ''}`} />
                    </Button>
                    <Button variant="outline" size="sm">
                      <Share2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div className="prose max-w-none">
                  <p className="text-gray-700 leading-relaxed">
                    {selectedArticle.content}
                  </p>
                </div>
                
                <div className="mt-8 pt-6 border-t">
                  <div className="flex items-center gap-4">
                    <div className="flex items-center gap-2">
                      <ThumbsUp className="h-5 w-5 text-green-500" />
                      <span className="text-sm text-gray-600">{selectedArticle.likes}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <MessageSquare className="h-5 w-5 text-blue-500" />
                      <span className="text-sm text-gray-600">{selectedArticle.comments} 条评论</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <Star className="h-5 w-5 text-yellow-500 fill-current" />
                      <span className="text-sm text-gray-600">{selectedArticle.rating}</span>
                    </div>
                  </div>
                  
                  <div className="mt-4">
                    <h4 className="font-medium mb-2">标签</h4>
                    <div className="flex flex-wrap gap-2">
                      {selectedArticle.tags.map((tag, index) => (
                        <Badge key={index} variant="secondary">
                          <Tag className="h-3 w-3 mr-1" />
                          {tag}
                        </Badge>
                      ))}
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    )
  }

  // 检查用户登录状态
  useEffect(() => {
    const user = localStorage.getItem('currentUser')
    if (!user) {
      alert('请先登录后使用此功能')
      router.push('/login')
      return
    }
    setCurrentUser(JSON.parse(user))
    setIsLoading(false)
  }, [router])

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-4 border-slate-300 border-t-slate-600 rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-slate-600">验证登录状态...</p>
        </div>
      </div>
    )
  }

  if (!currentUser) {
    return null
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="container mx-auto px-4 py-8">
        <div className="mb-8">
          <Button
            variant="ghost"
            className="mb-4"
            onClick={() => router.push("/")}
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            返回首页
          </Button>
          
          <div className="flex items-center gap-3 mb-4">
            <div className="p-2 bg-blue-500 text-white rounded-lg">
              <BookOpen className="h-6 w-6" />
            </div>
            <div>
              <h1 className="text-3xl font-bold">商业知识库</h1>
              <p className="text-gray-600">汇集创业与商业管理的精华知识</p>
            </div>
          </div>

          {/* Stats */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
            <Card>
              <CardContent className="p-4">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">知识文章</p>
                    <p className="text-2xl font-bold">240+</p>
                  </div>
                  <FileText className="h-8 w-8 text-blue-500" />
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-4">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">专家作者</p>
                    <p className="text-2xl font-bold">50+</p>
                  </div>
                  <User className="h-8 w-8 text-green-500" />
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-4">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">平均评分</p>
                    <p className="text-2xl font-bold">4.8</p>
                  </div>
                  <Star className="h-8 w-8 text-yellow-500" />
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Filters */}
          <div className="bg-white rounded-lg p-6 mb-8">
            <div className="flex items-center gap-4 mb-4">
              <div className="flex-1 relative">
                <Search className="h-5 w-5 absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
                <Input
                  placeholder="搜索知识文章、标签或作者..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
              <Button variant="outline" size="sm">
                <Filter className="h-4 w-4 mr-2" />
                筛选
              </Button>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div>
                <label className="block text-sm font-medium mb-2">分类</label>
                <select
                  value={selectedCategory}
                  onChange={(e) => setSelectedCategory(e.target.value)}
                  className="w-full border rounded-md px-3 py-2"
                >
                  {categories.map(category => (
                    <option key={category.id} value={category.id}>
                      {category.name}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium mb-2">难度</label>
                <select
                  value={selectedDifficulty}
                  onChange={(e) => setSelectedDifficulty(e.target.value)}
                  className="w-full border rounded-md px-3 py-2"
                >
                  {difficulties.map(difficulty => (
                    <option key={difficulty.id} value={difficulty.id}>
                      {difficulty.name}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium mb-2">类型</label>
                <select
                  value={selectedType}
                  onChange={(e) => setSelectedType(e.target.value)}
                  className="w-full border rounded-md px-3 py-2"
                >
                  {contentTypes.map(type => (
                    <option key={type.id} value={type.id}>
                      {type.name}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium mb-2">排序</label>
                <select
                  value={sortBy}
                  onChange={(e) => setSortBy(e.target.value)}
                  className="w-full border rounded-md px-3 py-2"
                >
                  {sortOptions.map(option => (
                    <option key={option.id} value={option.id}>
                      {option.name}
                    </option>
                  ))}
                </select>
              </div>
            </div>
          </div>
        </div>

        {/* Article List */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {loading ? (
            Array.from({ length: 6 }).map((_, i) => (
              <Card key={i} className="animate-pulse">
                <CardContent className="p-6">
                  <div className="h-4 bg-gray-200 rounded mb-2"></div>
                  <div className="h-4 bg-gray-200 rounded mb-4"></div>
                  <div className="h-20 bg-gray-200 rounded"></div>
                </CardContent>
              </Card>
            ))
          ) : (
            sortedArticles.map(article => {
              const categoryInfo = categories.find(c => c.id === article.category)
              const TypeIcon = getTypeIcon(article.type)
              
              return (
                <Card 
                  key={article.id} 
                  className="cursor-pointer hover:shadow-lg transition-shadow"
                  onClick={() => handleArticleClick(article)}
                >
                  <CardContent className="p-6">
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex items-center gap-2">
                        <TypeIcon className="h-4 w-4 text-gray-500" />
                        <Badge variant="outline" className="text-xs">
                          {article.type === "article" ? "文章" : 
                           article.type === "video" ? "视频" : 
                           article.type === "infographic" ? "图表" : 
                           article.type === "checklist" ? "清单" : "模板"}
                        </Badge>
                      </div>
                      <div className="flex items-center gap-1">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={(e) => {
                            e.stopPropagation()
                            handleBookmark(article.id)
                          }}
                        >
                          <Bookmark className={`h-4 w-4 ${article.bookmarked ? 'fill-current' : ''}`} />
                        </Button>
                      </div>
                    </div>

                    <h3 className="font-semibold mb-2 line-clamp-2">{article.title}</h3>
                    <p className="text-sm text-gray-600 mb-4 line-clamp-3">{article.summary}</p>

                    <div className="flex items-center gap-2 mb-4">
                      <Badge className={`${getDifficultyColor(article.difficulty)} text-white text-xs`}>
                        {article.difficulty === "beginner" ? "入门" : 
                         article.difficulty === "intermediate" ? "进阶" : "高级"}
                      </Badge>
                      {categoryInfo && (
                        <Badge variant="outline" className="text-xs">
                          {categoryInfo.name}
                        </Badge>
                      )}
                    </div>

                    <div className="flex items-center justify-between text-sm text-gray-500 mb-3">
                      <div className="flex items-center gap-1">
                        <User className="h-3 w-3" />
                        {article.author}
                      </div>
                      <div className="flex items-center gap-1">
                        <Clock className="h-3 w-3" />
                        {article.readTime}分钟
                      </div>
                    </div>

                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3 text-sm text-gray-500">
                        <div className="flex items-center gap-1">
                          <Heart className={`h-3 w-3 ${article.liked ? 'fill-current text-red-500' : ''}`} />
                          {article.likes}
                        </div>
                        <div className="flex items-center gap-1">
                          <Eye className="h-3 w-3" />
                          {article.views}
                        </div>
                        <div className="flex items-center gap-1">
                          <MessageSquare className="h-3 w-3" />
                          {article.comments}
                        </div>
                      </div>
                      <div className="flex items-center gap-1">
                        <Star className="h-3 w-3 text-yellow-500 fill-current" />
                        <span className="text-sm text-gray-600">{article.rating}</span>
                      </div>
                    </div>

                    <div className="mt-3 pt-3 border-t">
                      <div className="flex flex-wrap gap-1">
                        {article.tags.slice(0, 3).map((tag, index) => (
                          <Badge key={index} variant="secondary" className="text-xs">
                            {tag}
                          </Badge>
                        ))}
                        {article.tags.length > 3 && (
                          <Badge variant="secondary" className="text-xs">
                            +{article.tags.length - 3}
                          </Badge>
                        )}
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )
            })
          )}
        </div>

        {sortedArticles.length === 0 && !loading && (
          <div className="text-center py-12">
            <BookOpen className="h-12 w-12 text-gray-400 mx-auto mb-4" />
            <p className="text-gray-600 mb-2">未找到相关知识文章</p>
            <p className="text-sm text-gray-500">尝试调整搜索条件或筛选设置</p>
          </div>
        )}
      </div>
    </div>
  )
}